package com.shop.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.dto.WeChatOrders.UserOrdersSaveDto;
import com.shop.entity.pojo.Cart;
import com.shop.entity.pojo.Orders;
import com.shop.entity.pojo.OrdersDetail;
import com.shop.entity.vo.OrdersVo;
import com.shop.user.mapper.CartMapper;
import com.shop.user.mapper.OrdersDetailMapper;
import com.shop.user.mapper.OrdersMapper;
import com.shop.user.mapper.vo.OrdersVoMapper;
import com.shop.user.service.OrdersService;
import com.shop.user.service.WebSocketServer;
import com.shop.utils.common.enums.Code;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.result.Result;
import com.shop.utils.config.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService{

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrdersDetailMapper ordersDetailMapper;
    @Autowired
    private OrdersVoMapper ordersVoMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    public Result addOrders(UserOrdersSaveDto dto) {
        log.info("用户-添加订单");
        long start = System.currentTimeMillis();
        if (dto==null||dto.getUserPhone()==null||dto.getUserName()==null) {
            log.info("dto为空");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long userId = BaseContext.getCurrentId();
        if (userId==null) {
            log.info("userId为空");
            return Result.errorResult(Code.NEED_LOGIN);
        }
        List<Cart> carts1 = cartMapper.selectList(Wrappers.<Cart>lambdaQuery().eq(Cart::getUserId, userId));
        if (CollectionUtils.isEmpty(carts1) ||carts1.size()==Message.Check_Int_Null) {
            log.info("该用户的购物车数据为空");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }

        log.info("开始添加订单");
        String ordersId="JJ_shop"+ String.valueOf(System.currentTimeMillis());
        Orders orders=new Orders();
        Double allPrice = cartMapper.getAllPrice(userId);
        orders= orders.builder()
                .userId(userId)
                .userName(dto.getUserName())
                .userPhone(dto.getUserPhone())
                .ordersId(ordersId)
                .ordersPrice(allPrice)
                .ordersMemo(dto.getOrdersMemo())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        boolean testOrders = ordersMapper.addCart(orders);
        if (!testOrders) {
            log.info("添加失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }

        log.info("开始添加订单款式");
        List<Cart> carts = cartMapper.selectList(Wrappers.<Cart>lambdaQuery().eq(Cart::getUserId,userId));
        for (Cart cart : carts) {
            OrdersDetail detail=new OrdersDetail();
            detail.setWaresName(cart.getWaresName());
            detail.setStyleName(cart.getStyleName());
            detail.setCostMessage(cart.getCostMessage());
            detail.setCostPrice(cart.getCostPrice());
            detail.setWaresNumber(cart.getWaresNumber());
            detail.setOrdersId(ordersId);
            int insert = ordersDetailMapper.insert(detail);
            if (insert==Message.Check_Int_False) {
                log.info("订单添加失败");
                return Result.errorResult(Code.SERVER_ERROR);
            }
            int delete = cartMapper.deleteById(cart.getId());
            if (delete==Message.Check_Int_False) {
                log.info("修改用户购物车状态失败");
                return Result.errorResult(Code.SERVER_ERROR);
            }
        }
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + orders.getOrdersId());

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        long end = System.currentTimeMillis();
        log.info("用户添加订单进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result<List<OrdersVo>> getUserOrders() {
        log.info("用户-查看订单");
        long start = System.currentTimeMillis();
        Long userId = BaseContext.getCurrentId();
        log.info("userId:{}",userId);
        List<OrdersVo> ordersVo = ordersVoMapper.getOrders(userId);
        if (CollectionUtils.isEmpty(ordersVo)||ordersVo.size()==Message.Check_Int_False) {
            log.info("该用户并没有订单");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        long end = System.currentTimeMillis();
        log.info("用户查看订单进程完成，总耗时:{}",(end-start));
        return Result.okResult(ordersVo);
    }
}




